package com.hospital.wx.controller;

import com.hospital.wx.common.CommonResult;
import com.hospital.wx.pojo.ChatRequest;
import com.hospital.wx.pojo.ChatResponse;
import com.hospital.wx.pojo.SpeechRecognitionResult;
import com.hospital.wx.service.ChatService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;

@RestController
@RequestMapping("/ai")
@Slf4j
@Tag(name = "ChatController",description = "ai接口管理")
public class ChatController {

    @Autowired
    private ChatService chatService;

    @PostMapping("/chat")
    @Operation(summary = "AI对话接口")
    public ChatResponse chat(@RequestBody ChatRequest request) {
        String response = chatService.getAIResponse(request.getMessage());
        return new ChatResponse(response);
    }

    @PostMapping("/speech/recognize")
    @Operation(summary = "语音服务对接")
    public CommonResult recognizeSpeech(@RequestParam("audio")
                                        MultipartFile audioFile) {
        try {
            log.info("接收到的录音文件：{}", audioFile);
            SpeechRecognitionResult result = chatService.recognizeSpeech(audioFile);
            HashMap<String, String> map = new HashMap<>();
            map.put("error", "内容不合规");
            map.put("text", result.getText());
            map.put("reason", result.getRejectReason());

            if ("REJECTED".equals(result.getStatus())) {
                return CommonResult.failed("语音识别过程中审核出现不合规").put("result", map);
            }
            log.info("语音识别结果：{}", result.getText());
            return CommonResult.ok().put("text", result.getText());
        } catch (Exception e) {
            log.error("语音识别处理失败", e);
            return CommonResult.failed("语音识别处理失败");
        }
    }
}
